<template>
  <div class="online-monitor-box">
    <div class="left">
      <el-input v-model="keyWords" @change="queryChange" placeholder="请输入搜索关键字"></el-input>
      <el-tree-v2
          ref="treeRef"
          :data="treeData"
          :props="treeProps"
          :default-expanded-keys="defaultExpandedKeys"
          @node-click="nodeClick"
          :height="treeHeight"
      >
        <template #default="{ node,data }">
          <div>
            <span v-if="data.unitType && data.deviceStatus === 1" style="color: #008a00;padding-right: 4px;">稳定</span>
            <span v-else-if="data.unitType && data.deviceStatus !== 1" style="color: #c45656;padding-right: 4px;">不稳定</span>
            {{ data.name }}
            <span v-if="!data.unitType" style="color: #1c84c6;padding-right: 4px;">总数{{ data.countAllA }}</span>
            <span v-if="!data.unitType" style="color: #008a00;padding-right: 4px;">稳定{{ data.countInlineA }}</span>
            <span v-if="!data.unitType" style="color: #c45656;padding-right: 4px;">不稳定{{ data.countOfflineA }}</span>

          </div>
        </template>
      </el-tree-v2>
    </div>
    <div class="right" ref="rightRef">
      <div class="header-box">
        <div class="right-header" >
          <div style="display: flex;margin-right: auto;">
            <el-radio-group v-model="videoType" size="mini" @change="changeVideoType">
              <el-radio-button label="监控" value="live" />
              <el-radio-button label="回放" value="history" />
            </el-radio-group>
          </div>
           <span class="svg-icon-box" @click="changeTotalNumber(1)"
                 :class="[ totalNumber === 1?'active-icon':'']"><svg-icon icon-class="ak_fill"
           ></svg-icon></span>
          <span class="svg-icon-box" @click="changeTotalNumber(4)"
                :class="[ totalNumber === 4?'active-icon':'']"><svg-icon icon-class="all-fill"
          ></svg-icon></span>
          <span class="svg-icon-box" @click="changeTotalNumber(9)"
                :class="[totalNumber === 9?'active-icon':'']">
                        <svg-icon icon-class="gallery-view"></svg-icon>
                    </span>
          <span class="svg-icon-box" @click="toggle">
                            <svg-icon :icon-class="isFullscreen ? 'exit-fullscreen' : 'fullscreen'"/>
                       </span>

        </div>
      </div>
      <div class="right-body" ref="rightBodyRef" :class="[totalNumber === 9?'grid-9':totalNumber===4?'grid-4':'grid-1']">
        <div ref="monitorListRef" v-for="item in totalNumber" :key="item" class="item">
          <div class="play-box">
            <div class="play-header" v-if="playInfo[('k'+(item-1))]">
              <span style="padding-lef:2px;font-size: 12px;display: flex;margin-right: auto;">{{playList[(item-1)].playName}}</span>
              <Refresh style="width: 1em; height: 1em; margin-right: 8px;cursor: pointer;" @click="refreshVideo(item)"></Refresh>
<!--              <RefreshLeft style="width: 1em; height: 1em; margin-right: 8px;cursor: pointer;"></RefreshLeft>-->
<!--              <RefreshRight style="width: 1em; height: 1em; margin-right: 8px;cursor: pointer;"></RefreshRight>-->
              <Delete style="width: 1em; height: 1em; margin-right: 8px;cursor: pointer;" @click="delVideo(item)"></Delete>
            </div>
            <LivePlayer aspect='fullscreen' :stretch="true" :controls="false"
                        :videoUrl="playInfo[('k'+(item-1))]" live></LivePlayer>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="onlineMonitor">
import {getLiveInfo, listAddressUnit,getHistoryLiveInfo} from "@/api/wvp/onlineMonitor";
import {useFullscreen} from '@vueuse/core'
import SvgIcon from "@/components/SvgIcon/index.vue";
import {listAddressUnitExcludeChild} from "@/api/wvp/addressUnit";
// import LivePlayer from '@liveqing/liveplayer-v3'
import LivePlayer from '@/components/VideoPlayer/flv.vue'
import {Delete, Refresh, RefreshLeft, RefreshRight} from "@element-plus/icons-vue";
import {parseTime} from "@/utils/ruoyi";


defineComponent(LivePlayer)

const {proxy} = getCurrentInstance();
const treeRef = ref()
const treeData = ref()
const oldTreeData = ref()
const keyWords = ref("")
const totalNumber = ref(1)
const monitorListRef = ref()
const rightRef = ref()
const rightBodyRef = ref()
const playList = ref([])
const playInfo = ref({
  k0: "",
  k1: "",
  k2: "",
  k3: "",
  k4: "",
  k5: "",
  k6: "",
  k7: "",
  k8: "",
  k9: "",
})
const {isFullscreen, enter, exit, toggle} = useFullscreen(rightBodyRef);
const treeProps = {
  label: "name",
  value: "id",
  children: "children"
}
const defaultExpandedKeys = ref(['A1'])
const queryChange = (query) => {
  // treeRef.value.filter(query)
  treeRef.value.setData(filterTree(query,JSON.parse(JSON.stringify(oldTreeData.value))))
}

const filterTree = (keyWords,treeData)=>{
  const arr=[];
  treeData.forEach((item)=>{
     if(item.name.includes(keyWords)){
       arr.push(item);
     }else if(item.children && item.children.length > 0) {
       let children=filterTree(keyWords,item.children)
       if(children && children.length > 0) {
         item.children=children;
         arr.push(item);
       }
     }
  })
  return arr;
}

const filterMethod = (query, node) => {
  return node.name.includes(query)
}
const changeTotalNumber = (n) => {
  totalNumber.value = n;
  for (let i = 9; i > n; i--) {
     delVideo(i);
  }
}

const refreshVideo=(index)=>{
  // playInfo.value[('k'+(index-1))]
  index-=1
  const key = 'k' + index;
  playInfo.value[key]="";
 const oldId= playList.value[index].oldId;
  getLiveInfo(oldId).then((liveInfo) => {
    playInfo.value[key] = liveInfo.data.hdAddress;
    playList.value[index].playUrl=liveInfo.data.hdAddress;
  })
}

const delVideo =(index)=>{
  index-=1
  const key = 'k' + index;
  playInfo.value[key]="";
  delete playList.value[index]
}


const videoType = ref('live')

const changeVideoType = () => {
  playList.value=[];
  playInfo.value={};
}

const nodeClick = (data, node, e) => {
  if (data.unitType) {
    if(totalNumber.value !== 1){
      let exeit = false
      let count = 0;
      playList.value.forEach(item => {
        if (item && item.id === data.id) {
          exeit = true;
        }
        if(item){
          count++;
        }
      })
      if (exeit || count >= totalNumber.value) {
        return;
      }
    }
    if(videoType.value === 'live'){
      // if(data.deviceStatus !== 1){
      //   return;
      // }
      getLiveInfo(data.oldId).then((liveInfo) => {
        setPlay(data,liveInfo)
      })
    }else{
      const now=new Date();
      now.setTime(now.getTime() - 24*60*60*1000);
      const startTime=parseTime(now.getTime());
      const stopTime=parseTime(new Date().getTime());
      getHistoryLiveInfo(data.oldId,{startTime,stopTime}).then(liveInfo=>{
        liveInfo.data.hdAddress=liveInfo.data.url;
        setPlay(data,liveInfo)
      })
    }

  }

}

function setPlay(data,liveInfo){

  if(totalNumber.value === 1){
    let playUrl = liveInfo.data.hdAddress;
    const key = 'k0';
    playInfo.value[key] = playUrl;
    playList.value.splice(playUrl.indexOf(key), 1,{
      id: data.id,
      oldId: data.oldId,
      playUrl: playUrl,
      playName: data.name +'-'+data.deviceNumber
    });
    return;
  }

  let playUrl = liveInfo.data.hdAddress;
  let index = playList.value.length;
  let preBoo =false;
  for (let i = 0; i < playList.value.length; i++) {
    if(!playList.value[i]) {
      index = i;
      preBoo=true;
      break;
    }
  }
  const key = 'k' + index;
  playInfo.value[key] = playUrl;
  if(preBoo){
    playList.value[index] = {
      id: data.id,
      oldId: data.oldId,
      playUrl: playUrl,
      playName: data.name +'-'+data.deviceNumber
    };
  }else{
    playList.value.push({
      id: data.id,
      oldId: data.oldId,
      playUrl: playUrl,
      playName: data.name +'-'+data.deviceNumber
    })
  }
}


function getCountAll(response, actObj) {
  const mapObj = {};
  const deviceList = response.data.filter(item => item.unitType);
  deviceList.forEach(item => {
    if (!mapObj[item.parentId]) {
      mapObj[item.parentId] = 0;
    }
    mapObj[item.parentId] += 1;
  })

  const countObj = {}
  Object.keys(mapObj).forEach(item => {
    actObj[item].split(',').forEach(id => {
      if (!countObj['A' + id]) {
        countObj['A' + id] = 0;
      }
      countObj['A' + id] += mapObj[item];
    })
    countObj[item] = mapObj[item];
  })
  return countObj;
}

function getCountInline(response, actObj) {
  const mapObj = {};
  const deviceList = response.data.filter(item => item.unitType && item.deviceStatus !== 0);
  deviceList.forEach(item => {
    if (!mapObj[item.parentId]) {
      mapObj[item.parentId] = 0;
    }
    mapObj[item.parentId] += 1;
  })

  const countObj = {}
  Object.keys(mapObj).forEach(item => {
    actObj[item].split(',').forEach(id => {
      if (!countObj['A' + id]) {
        countObj['A' + id] = 0;
      }
      countObj['A' + id] += mapObj[item];
    })
    countObj[item] = mapObj[item];
  })
  return countObj;
}

function getCountOffline(response, actObj) {
  const mapObj = {};
  const deviceList = response.data.filter(item => item.unitType && item.deviceStatus === 0);
  deviceList.forEach(item => {
    if (!mapObj[item.parentId]) {
      mapObj[item.parentId] = 0;
    }
    mapObj[item.parentId] += 1;
  })

  const countObj = {}
  Object.keys(mapObj).forEach(item => {
    actObj[item].split(',').forEach(id => {
      if (!countObj['A' + id]) {
        countObj['A' + id] = 0;
      }
      countObj['A' + id] += mapObj[item];
    })
    countObj[item] = mapObj[item];
  })
  return countObj;
}

listAddressUnit().then(response => {
  const actObj = {}
  const unitList = response.data.filter(item => !item.unitType);
  unitList.forEach(item => {
    if (!actObj[item.id]) {
      actObj[item.id] = item.ancestors;
    }
  })
  const countAll = getCountAll(response, actObj);
  const countInline = getCountInline(response, actObj);
  const countOffline = getCountOffline(response, actObj);
  response.data.forEach(item => {
    if (!item.unitType) {
      let countAllA = countAll[item.id];
      if (!countAll) {
        countAllA = 0;
      }
      item.countAllA = countAllA;

      let countOfflineA = countOffline[item.id];
      if (!countOfflineA) {
        countOfflineA = 0;
      }
      item.countOfflineA = countOfflineA;

      let countInlineA = countInline[item.id];
      if (!countInlineA) {
        countInlineA = 0;
      }
      item.countInlineA = countInlineA;
    }
  })
  oldTreeData.value = proxy.handleTree(response.data, "id");
  treeData.value = JSON.parse(JSON.stringify(oldTreeData.value));
});


const screenHeight = ref(window.innerHeight);
const treeHeight = ref(10);

function handleResize() {
  screenHeight.value = window.innerHeight;
  // console.log(screenHeight.value);
  treeHeight.value = screenHeight.value - treeRef.value.$el.getBoundingClientRect().top;


  // console.log(treeHeight.value);
}

onMounted(() => {
  handleResize()
  window.addEventListener('resize', handleResize);
});
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.online-monitor-box {
  display: flex;
  height: 100%;
}

.online-monitor-box .left {
  width: 340px;
  padding: 20px 0 0 20px;
  height: 100%;
  box-sizing: border-box;
  position: absolute;
}

.online-monitor-box .right {
  width: calc(100% - 380px);
  height: inherit;
  position: absolute;
  left: 380px;
  top: 0;
  bottom: 0;
  right: 0;
}

.online-monitor-box .right .right-body {
  display: grid;
  height: 100%;
  width: 100%;
  background: #000000;
  padding-bottom: 44px;
}

.online-monitor-box .right .header-box {
  width: 100%;
  position: relative;

}

.online-monitor-box .right .header-box .right-header {
  right: 20px;
  background: #f2f2f2;
  z-index: 99999;
  display: flex;
  align-items: center;
  padding: 4px;
}


.online-monitor-box .right .grid-4 {
  grid-template-columns: 1fr 1fr;
}
.online-monitor-box .right .grid-1 {
  grid-template-columns: 1fr;
}

.online-monitor-box .right .grid-9 {
  grid-template-columns: 1fr 1fr 1fr;
}

.active-icon {
  opacity: unset !important;
}

.svg-icon-box {
  opacity: 0.6;
  cursor: pointer;
  margin-right: 6px;
}


.right-body .item {
  width: 100%;
  height: 100%;
  padding: 6px;
  box-sizing: border-box;
  border: 1px solid #fff;
}

.right-body .item .play-box {
  position: relative;
  width: 100%;
  height: 100%;
}
.right-body .item .play-box .play-header{
  position: absolute;
  top: 0;
  height: 20px;
  width: 100%;
  z-index: 9999999;
  display: flex;
  background: #f2f2f2;
  opacity: 0.6;
  justify-content: right;
  align-items: center;
}
</style>
